//还未显示机构和日期输入框
var hasOrganAndDateInput = false;
var isInitTree = false;

$(function() {

	var str = '<option value="1">工业领域</option>';
	str += '<option value="2">金融领域</option>';
	str += '<option value="3">电信领域</option>';
	str += '<option value="4">智慧城市</option>';
	$('[name="businessType"]').append($('<option value="-1">请选择</option>'+str));
	$('[name="businessType"]').chosen({
		width: "100%",
		search_contains: true,
		
	});
	
	var str = '<option value="1">机构1</option>';
	str += '<option value="2">机构2</option>';
	str += '<option value="3">机构3</option>';
	str += '<option value="4">机构4</option>';
	$('[name="organ"]').append($(str));
	$('[name="organ"]').chosen({
		width: "100%",
		search_contains: true,
		
	});
	
	//初始化bootstrap table
	intiTable("#table");
	
	//模糊查询
	$("#search-btn").click(function(){
		refreshTable();
	});
	
	

	// --------
});

//刷新表格
function refreshTable(){
	var params = $("#search-form").serializeJson();
	params.state = 0;
	$('#table').bootstrapTable("refresh", {
		query : params
	});	
}

var download = '<a href="javascript:void(0);" title="下载" class="download"><span class="glyphicon glyphicon-download"></span></a>';
var col = [
	{
		field : "key",
		title : "编号",
		align : "center",
		valign : "middle",
		formatter : function(value, row, index) {
			return index+1;
		}
	},
	{
		field : "reportOldName",
		title : "报告名称",
		align : "center",
		valign : "middle",
	},
	{
		field : "author",
		title : "编写人",
		align : "center",
		valign : "middle",
	},
	{
		field : "uploadBy",
		title : "上传人",
		align : "center",
		valign : "middle",
	},
	{
		field : "reportDescribe",
		title : "报告描述",
		align : "center",
		valign : "middle",
		width:200,
		class:'colStyle',
		formatter:paramsMatter,
	},
	{
		field : "operation",
		title : "操作",
		clickToSelect : false,
		align : "center",
		valign : "middle",
		events : "operateEvents",
		formatter : function(value, row, index) {
			return download;
		}
	}];

//bootstrap table绑定数据
function intiTable(selector){
	var $table = $(selector);
	$table.bootstrapTable({ // 对应table标签的id
		url : ctxPath + "/report/word/queryDownloadReport",
		cache : false, // 设置为 false 禁用 AJAX 数据缓存， 默认为true
		pagination : true, // 分页
		paginationLoop : true,// 设置为 true 启用分页条无限循环的功能。
		striped : true,//隔行变色
		clickToSelect : true,// 点击选择
		pageNumber : 1,// 如果设置了分页，首页页码
		pageSize : 10,// 如果设置了分页，页面数据条数
		pageList : [ 15, 30, 45 ], // 如果设置了分页，设置可供选择的页面数据条数。设置为All
		// 则显示所有记录。
		paginationPreText : '‹',// 指定分页条中上一页按钮的图标或文字,这里是<
		paginationNextText : '›',// 指定分页条中下一页按钮的图标或文字,这里是>
		method : 'post',
		contentType : 'application/x-www-form-urlencoded; charset=UTF-8',
		sidePagination: "server", //服务端处理分页
		queryParams : function(params) { // 自定义参数
			params.fileType = "docx";
			params.state = 0;
			return params;
		},
		responseHandler : function(result){
			return result.data;
		},
		columns : col,
		onLoadError : function() { // 加载失败时执行
			failMsg("加载数据失败！");
		}
	});
}

//bootstrap table的操作列按钮事件
window.operateEvents = {
	"click .download" : function(e, value, row, index) {
		var flag = false;
		if(!hasOrganAndDateInput){
			flag = fillOrganAndDate();
		}else{
			flag = true;
		}
		//执行下载
		if(flag){
			var data = {
					"fileName":row.reportOldName,
					"downloadFilePath":row.filePath
			}
			//执行校验,不下载文件不存在的数据
			var bool = false;
			$.ajax({
			 	type: "POST",
			 	url: ctxPath+"/report/word/downloadBeforCheck",
			 	data: data,
			 	async: false,
			 	contentType: 'application/x-www-form-urlencoded;charset=utf-8',
			 	dataType: "json",
			 	success: function (result) {
			 		if (result.code == 1) {
						bool = true;
						return;
					}
			 		layer.msg(result.msg, {
						icon: 2,
						btnAlign: 'c',
						btn: ["关闭"],
						time:false
					});
			 	}
			});
			if (!bool) {
				return;
			}
			//
			var date = $("[name=date]").val();
			var organ = $("[name=organCode]").val();
			if(!data || !organ){
				failMsg("请选择组织机构和日期！！！");
				return false;
			}
			//创建临时表单
			var $tempForm = $("<form style='display:none;'></form>");
			var $organ = $("<input name='organCode' type='hidden' value='" + organ
						+ "'/>");
			var $date = $("<input name='date' type='hidden' value='" + date
					+ "'/>");
			var $wordNames = $("<input name='wordNames' type='hidden' value='" + row.reportName
					+ "'/>");
			var $wordOldNames = $("<input name='wordOldNames' type='hidden' value='" + row.reportOldName
					+ "'/>");
			
			$tempForm.append($organ);
			$tempForm.append($date);
			$tempForm.append($wordNames);
			$tempForm.append($wordOldNames);
			$("body").append($tempForm);
			$tempForm.attr("action", ctxPath+"/report/word/downLoadWord");
			$tempForm.attr("method", "post");
			$tempForm.submit();
			$tempForm.remove();
		}
			
	},
}


//下载模板
function fillOrganAndDate(){
	if(!treeId){
		failMsg("请在系统参数配置中   配置机构树！！！")
		return false;
	}else{
		if(!isInitTree){
			(function(treeId){
            	var html = '<tree url="'+ctxPath+'/report/tree/getDicJson" name="organCode" id="organId" data-isCheck="false" data-optionid="'+treeId+'" hiddename="organName" />';
            	$("#treeDiv").append(html);
            	newTree.render('organId', {
                    hasRoot: false,
                    delBtnGroup: true,
                    idKey: 'key',
                    pIdKey: 'parentId',
                    nameKey: 'value',
                    title : "key"
                    //onclickNode:organClick
                });
			})(treeId);
			isInitTree = true;
		}
	}
	layer.open({
		type: 1, 
		title : "请选择组织机构和日期",
		area : [ "40%", "70%" ],
		content: $("#download"),
		btnAlign: 'c',
		btn: ["确定"],
		yes:function(index){
			var params = $("#downLoadForm").serializeJson();
			var date = params["paramDate"];
			var organ = params["organCode"];
			if(!date || !organ){
				failMsg("请选择组织机构和日期！！！");
				return false;
			}
			if(!hasOrganAndDateInput){
				//第一次保存机构和日期    显示按钮  并绑定事件
				$("#organAndDate").removeClass("hidden")
				$("#organAndDate .btn-primary").click(function(){
					fillOrganAndDate();
				})
			}
			var offset = $("#organAndDate").offset();
		    var bodyWidth = $("body").width();
		    var bodyHeigh = $("body").height();
		    layer.close(index);
		    $('<i class="glyphicon glyphicon-cog" style="color:red;"></i>').fly({
			      speed : 0.5,
			      start: {top: bodyHeigh/2, left: bodyWidth/2,width:50,height:50},
			      end: {top: offset.top+10, left:offset.left+10,width:0,height:0},
			      onEnd: function(){
			    	hasOrganAndDateInput = true;
			    	$("[name=date]").val(date);
					$("[name=organCode]").val(organ);
			        this.destroy();
			      }
		    });
		    return true;
		}
	});
}

//悬浮显示值
function paramsMatter(value, row, index) {
	if (value == undefined) {
		return;
	}
	var values = value;
	values = values.replace(/\s+/g,'&nbsp;')//替换空格
	values = values.replace(/\},/,'},\n');//换行
	var span=document.createElement('span');
	span.setAttribute('title',values);
	span.innerHTML = value;
	return span.outerHTML;
}










